/*                                    _
 *   ___ _ __ ___ _ __ ___   ___   __| |
 *  / __| '__/ __| '_ ` _ \ / _ \ / _` |
 *  \__ \ |  \__ \ | | | | | (_) | (_| |
 *  |___/_|  |___/_| |_| |_|\___/ \__,_|                                  
 *
 * |_  _ | _  _  _ _   _ _  _  _|   | _ 
 * | |(/_||_)(/_| _\  | | |(_)(_||_||(/_
 *        |                             
 */


new survivorCount;
new survivorIndex[MAXPLAYERS+1];

SurvivorIndex_OnPluginStart()
{
	_SI_HookEvents();
}

_SI_HookEvents()
{
	// these hooks do nothing but keeping the Survivor Index up to date
	HookEvent("round_start", SurvivorIndex_Event);
	HookEvent("round_end", SurvivorIndex_Event);
	HookEvent("player_spawn", SurvivorIndex_Event);
	HookEvent("player_disconnect", SurvivorIndex_Event);
	HookEvent("player_death", SurvivorIndex_Event);
	HookEvent("player_bot_replace", SurvivorIndex_Event);
	HookEvent("bot_player_replace", SurvivorIndex_Event);
	HookEvent("defibrillator_used", SurvivorIndex_Event);
	HookEvent("player_team", IndexDelayed_Event);
}

public IndexDelayed_Event(Handle:event, const String:name[], bool:dontBroadcast)
{
	CreateTimer(SURVIVORINDEX_REBUILD_DELAY, RebuildIndex_Timer);
}

public Action:RebuildIndex_Timer(Handle:timer)
{
	StateHelpers_RebuildSurvIndex();
}

public SurvivorIndex_Event(Handle:event, const String:name[], bool:dontBroadcast)
{
	StateHelpers_RebuildSurvIndex();
}

StateHelpers_RebuildSurvIndex()
{
	if (!IsServerProcessing()) return;

	survivorCount = 0;
	for (new target = 1; target <= MaxClients; target++)
	{
		survivorIndex[target] = 0;
		
		if (!IsClientInGame(target)) continue;
		if (GetClientTeam(target) != 2) continue;
		if (GetClientHealth(target) < 1) continue;
		
		survivorCount++;
		survivorIndex[survivorCount] = target;
	}
	
	/* Something wrong with those Macros. Downtown, fix your insane shit :D
	FOR_EACH_SURVIVOR(i)
	{
		survivorCount++;
		survivorIndex[survivorCount] = i;
	}
	*/
}